#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>
#include <sys/select.h>

#define KEY_RELEASE 0
#define KEY_PRESS 1

int main(void) {
    struct input_event ev;
    fd_set readfds;
    int fd, ret;

    fd = open("/dev/input/event0", O_RDONLY);  // replace 'event0' with your input device event number
    if (fd < 0) {
        perror("Cannot open device");
        return 1;
    }

    while (1) {
        FD_ZERO(&readfds);
        FD_SET(fd, &readfds);

        ret = select(fd + 1, &readfds, NULL, NULL, NULL);
        if (ret < 0) {
            perror("Error using select");
            return 1;
        }

        if (FD_ISSET(fd, &readfds)) {
            read(fd, &ev, sizeof(struct input_event));

            if (ev.type == EV_KEY) {
                if (ev.value == KEY_PRESS) {
                    printf("Key %d pressed at %ld.%06ld\n", ev.code, ev.time.tv_sec, ev.time.tv_usec);
                } else if (ev.value == KEY_RELEASE) {
                    printf("Key %d released at %ld.%06ld\n", ev.code, ev.time.tv_sec, ev.time.tv_usec);
                }
            }
        }
    }

    close(fd);
    return 0;
}
